<template>
  <el-container class="temple">
    <el-drawer
      :with-header="false"
      :visible.sync="drawerVisible"
      size="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :append-to-body="true"
      :wrapper-closable="false"
      style="z-index: 1000;"
    >
      <el-header>{{ textMap[dialogStatus] }}项目</el-header>
      <el-main>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-width="100px"
          style="width: 100%"
        >
          <el-row>
            <el-col :span="8">
              <el-divider content-position="center">基本信息</el-divider>
              <el-form-item
                label="项目编号"
                prop="ProjectCode"
              >
                <el-input v-model="temp.ProjectCode" />
              </el-form-item>
              <el-form-item
                label="项目名称"
                prop="ProjectName"
              >
                <el-input v-model="temp.ProjectName" />
              </el-form-item>
              <el-form-item label="项目时间" prop="datepicker">
                <el-date-picker v-model="temp.datepicker" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
              </el-form-item>
              <el-form-item label="预计费用">
                <el-input v-model="temp.AllFee" />
              </el-form-item>
              <el-form-item label="负责人">
                <p class="for_form_item" @click="chooseperson">
                  <el-tag
                    v-for="(tag,index) in persontags"
                    :key="tag.Id"
                    closable
                    @close="handlePersonClose(index)"
                  >
                    {{ tag.Name }}
                  </el-tag>
                </p>
              </el-form-item>
              <el-form-item label="状态">
                <el-select
                  v-model="temp.Status"
                  placeholder="请选择项目状态"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="部门">
                <p class="for_form_item" @click="handleSelectDepart">
                  <el-tag v-for="item in selectedDepartments" :key="item.Id">{{ item.OrgName }}</el-tag>
                </p>
              </el-form-item>
              <el-form-item label="上传附件">
                <el-upload
                  ref="upload"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemove"
                  :file-list="successfiles"
                  :action="uploadurl"
                  :headers="uploadheaders"
                  :data="uploaddata"
                  :multiple="true"
                  list-type="text"
                  :show-file-list="true"
                  :on-preview="handlePreview"
                  :on-success="uploadSuccess"
                >
                  <el-button
                    size="small"
                    plain
                    style="width: 100%"
                  ><i class="el-icon-upload2" /> 选择附件上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <div style="padding-left:10px">
                <el-divider content-position="center">其它说明</el-divider>
                <Tinymce v-if="drawerVisible" ref="peojectNote" v-model="temp.Note" />
              </div>
            </el-col></el-row>
        </el-form>
      </el-main>
      <el-footer>
        <div>
          <el-button @click="drawerVisible = false">返回</el-button>
          <el-button
            type="primary"
            :loading="isLoading"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >提交</el-button>
        </div>
        <div />
      </el-footer>
    </el-drawer>
    <SelectPerson
      ref="selectpersonref"
      :echo-list="persontags"
      @allSelect="personResult"
    />

    <selectdepartment ref="selectdepartment" :echo-list="selectedDepartments" @submitSelect="selectedDepart" />
  </el-container>
</template>

<script>
import SelectPerson from '@/views/components/permissions/singlechoiceperson'
import Tinymce from '@/components/Tinymce'
import selectdepartment from '@/views/components/singlechoicedepartment'
import { config } from '@/utils/requestconfig'
import { getToken } from '@/utils/auth'
import { addProject, editProject, FindProjectById } from '@/api/project/project'
export default {
  components: { SelectPerson, Tinymce, selectdepartment },
  props: { },
  data() {
    return {
      isLoading: false,
      /** *****************************附件参数****************************/
      fileList: [], // {name: 'food.jpeg',url: 'https'}
      successfiles: [], // 上传成功的文件，确定后，保存在服务器数据库中
      uploadurl: config.webapi + 'upload/UploadFiles',
      uploadheaders: { Authorization: getToken() },
      uploaddata: { dir: 'uploadFile' },
      /** ***********select***************/
      options: [
        {
          value: 1,
          label: '启动中'
        },
        {
          value: 2,
          label: '进行中'
        },
        {
          value: 3,
          label: '验收中'
        },
        {
          value: 4,
          label: '已结束'
        }
      ],
      /** *****************Tags************************/
      tagType: { success: 'success', warning: 'warning', danger: 'danger' }, // tag显示类型
      persontags: [],
      drawerVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      /** ************Form****************** */
      temp: {
        Id: '',
        Status: 1, // 项目状态1启动中2 进行中3 验收中4 已结束
        // 项目参数
        ProjectCode: '', // 项目编号
        ProjectName: '', // 项目名称
        MainPersonId: '', // 项目负责人ID
        MainPersonName: '', // 项目负责人姓名
        DepartmentName: '', // 项目所属部门
        DepartmentId: '', // 项目所属部门ID
        StartDate: '',
        EndDate: '',
        datepicker: [],
        Note: '',
        AllFee: '' // 项目预计总费用
      },
      formData: {
        Project: {},
        AttchLists: []
      },
      rules: {
        ProjectCode: [
          { required: true, message: '项目编号必填', trigger: 'blur' }
        ],
        ProjectName: [
          { required: true, message: '项目名称必填', trigger: 'blur' }
        ],
        datepicker: [{ type: 'array', required: true, message: '请选择日期', trigger: 'change' }]
      },
      selectedDepartments: []
    }
  },
  created() {
  },
  methods: {
    handlePersonClose(index) {
      this.persontags.splice(index, 1)
    },
    chooseperson() {
      this.$refs.selectpersonref.singlepersonref()
    },
    // 打开新增弹窗
    addopen(id) {
      this.init()
      // 新增项目根据选择的分组自动回显所属分组
      this.dialogStatus = 'create'
      this.drawerVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 选择人员回调方法
    personResult(persontaglist) {
      this.persontags = persontaglist
      if (persontaglist.length > 0) {
        this.temp.MainPersonName = persontaglist[0].Name
        this.temp.MainPersonId = persontaglist[0].Id
      } else {
        this.temp.MainPersonName = ''
        this.temp.MainPersonId = ''
      }
    },
    // 初始化
    init() {
      this.persontags = [] // 人员
      this.successfiles = []
      this.fileList = []
      this.temp = {
        Id: '',
        Status: 1, // 项目状态1启动中2 进行中3 验收中4 已结束
        // 项目参数
        ProjectCode: '', // 项目编号
        ProjectName: '', // 项目名称
        MainPersonId: '', // 项目负责人ID
        MainPersonName: '', // 项目负责人姓名
        DepartmentName: '', // 项目所属部门
        DepartmentId: '', // 项目所属部门ID
        StartDate: '',
        EndDate: '',
        datepicker: [],
        Note: '',
        AllFee: '' // 项目预计总费用
      }
    },
    // 新增保存
    createData() {
      this.isLoading = true
      var _this = this

      this.$nextTick(() => {
        // 同时存储附件和表单信息
        _this.temp.AllFee = parseFloat(_this.temp.AllFee || 0)
        if (this.temp.datepicker.length === 2) {
          _this.temp.StartDate = this.temp.datepicker[0]
          _this.temp.EndDate = this.temp.datepicker[1]
        }
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            _this.temp.Attachments = this.successfiles
            addProject(_this.temp).then(() => {
              _this.drawerVisible = false
              _this.init()
              _this.$emit('savesuccess')
              _this.isLoading = false
            })
          } else {
            _this.isLoading = false
          }
        })
      })
      setTimeout(() => {
        _this.isLoading = false
      }, 5000)
    },
    // 打开修改弹窗
    editOpen(row) {
      // this.init()
      FindProjectById(row.Id).then(res => {
        this.temp = res.Data
        // 人员回显
        if (this.temp.MainPersonId) {
          this.persontags = [{ Id: this.temp.MainPersonId, Name: this.temp.MainPersonName }]
        }
        if (this.temp.DepartmentId) {
          this.selectedDepartments = [{ Id: this.temp.DepartmentId, OrgName: this.temp.DepartmentName }]
        }
        if (this.temp.StartDate && this.temp.EndDate) {
          this.temp.datepicker = [this.temp.StartDate, this.temp.EndDate]
        }
        this.successfiles = this.temp.Attachments
        // 打开弹窗
        this.dialogStatus = 'update'
        this.drawerVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    // 修改保存
    updateData() {
      var _this = this
      _this.isLoading = true
      if (this.temp.datepicker.length === 2) {
        _this.temp.StartDate = this.temp.datepicker[0]
        _this.temp.EndDate = this.temp.datepicker[1]
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            _this.temp.Note = _this.$refs.peojectNote.getContent()
            console.log(' _this.Note', _this.Note)
            _this.temp.Attachments = this.successfiles
            editProject(_this.temp).then(() => {
              _this.drawerVisible = false
              _this.init()
              _this.isLoading = false
              _this.$emit('savesuccess')
            })
          } else {
            _this.isLoading = false
          }
        })
      })
      setTimeout(() => {
        _this.isLoading = false
      }, 5000)
    },
    /** *************************附件******************************/
    // 移除上传成功附件列表
    handleRemove(file, fileList) {
      const _this = this
      _this.successfiles = _this.successfiles.filter(
        item => item.name !== file.name
      )
      if (file.Id === undefined || file.Id === '' || file.Id === null) {
        return
      } else {
        // deleteSysAttch(file.Id).then(res => {
        //   this.$message({
        //     type: 'success',
        //     message: '删除成功!'
        //   })
        // })
      }
    },
    // 删除附件
    beforeRemove(file, fileList) {
      return this.$confirm(`您确定要移除 ${file.name}文件吗？`)
    },
    // 附件上传成功后的回调函数
    uploadSuccess(res, file) {
      const that = this
      if (res.IsSuccess) {
        if (res.Data != null) {
          that.successfiles.push(...res.Data)
        }
      } else {
        this.$message.warning(res.Msg)
      }
    },
    handleSelectDepart() {
      this.selectedDepartments = []
      if (this.temp.DepartmentId) {
        this.selectedDepartments = [{ Id: this.temp.DepartmentId, OrgName: this.temp.DepartmentName }]
      }
      this.$refs.selectdepartment.showSingleDepartmentDialog()
    },
    selectedDepart(depart) {
      this.selectedDepartments = depart
      if (depart.length > 0) {
        this.temp.DepartmentId = depart[0].Id
        this.temp.DepartmentName = depart[0].OrgName
      } else {
        this.temp.DepartmentId = ''
        this.temp.DepartmentName = ''
      }
    },
    handlePreview(file) {
      window.open(file.previewPath)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-main {
  height: calc(100vh - 120px);
}
.select-person {
  height: auto;
  background-color: #fafafa;
}
.el-divider--horizontal {
  margin: 30px 0;
}
</style>
